'use client'

import { useState } from 'react'
import { Lock, Shield, Bell, Eye, EyeOff, Save, Check, AlertTriangle } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Separator } from '@/components/ui/separator'
import { Switch } from '@/components/ui/switch'
import { Label } from '@/components/ui/label'

export default function AccountPage() {
  const [isChangingPassword, setIsChangingPassword] = useState(false)
  const [isSaving, setIsSaving] = useState(false)
  const [showCurrentPassword, setShowCurrentPassword] = useState(false)
  const [showNewPassword, setShowNewPassword] = useState(false)
  const [showConfirmPassword, setShowConfirmPassword] = useState(false)

  // 密码表单状态
  const [passwordForm, setPasswordForm] = useState({
    currentPassword: '',
    newPassword: '',
    confirmPassword: ''
  })

  // 安全设置状态
  const [securitySettings, setSecuritySettings] = useState({
    twoFactorAuth: true,
    loginNotifications: true,
    suspiciousActivityAlerts: true,
    sessionTimeout: 30, // 分钟
    maxLoginAttempts: 5
  })

  // 通知设置状态
  const [notificationSettings, setNotificationSettings] = useState({
    emailNotifications: true,
    pushNotifications: false,
    systemUpdates: true,
    securityAlerts: true,
    marketingEmails: false
  })

  // 账户活动状态
  const [accountActivity] = useState([
    {
      id: 1,
      action: '登录成功',
      location: '北京市朝阳区',
      ip: '192.168.1.100',
      device: 'Chrome 120.0.0.0 / Windows 10',
      timestamp: '2024-12-15 14:30:25',
      status: 'success'
    },
    {
      id: 2,
      action: '密码修改',
      location: '北京市朝阳区',
      ip: '192.168.1.100',
      device: 'Chrome 120.0.0.0 / Windows 10',
      timestamp: '2024-12-14 16:20:15',
      status: 'success'
    },
    {
      id: 3,
      action: '登录失败',
      location: '上海市浦东新区',
      ip: '203.208.60.1',
      device: 'Safari 17.1 / macOS',
      timestamp: '2024-12-13 09:15:30',
      status: 'failed'
    }
  ])

  const handlePasswordChange = async () => {
    if (passwordForm.newPassword !== passwordForm.confirmPassword) {
      alert('新密码和确认密码不匹配')
      return
    }

    if (passwordForm.newPassword.length < 8) {
      alert('新密码长度至少8位')
      return
    }

    setIsSaving(true)
    // 模拟保存操作
    await new Promise(resolve => setTimeout(resolve, 1000))
    setIsSaving(false)
    setIsChangingPassword(false)
    setPasswordForm({
      currentPassword: '',
      newPassword: '',
      confirmPassword: ''
    })
    // 这里可以添加成功提示
  }

  const handleSecuritySettingChange = (key: string, value: any) => {
    setSecuritySettings(prev => ({
      ...prev,
      [key]: value
    }))
  }

  const handleNotificationSettingChange = (key: string, value: boolean) => {
    setNotificationSettings(prev => ({
      ...prev,
      [key]: value
    }))
  }

  const getStatusBadge = (status: string) => {
    switch (status) {
      case 'success':
        return <Badge className="bg-green-100 text-green-800">成功</Badge>
      case 'failed':
        return <Badge className="bg-red-100 text-red-800">失败</Badge>
      case 'warning':
        return <Badge className="bg-yellow-100 text-yellow-800">警告</Badge>
      default:
        return <Badge variant="secondary">未知</Badge>
    }
  }

  const getActionIcon = (action: string) => {
    switch (action) {
      case '登录成功':
        return <Check className="h-4 w-4 text-green-500" />
      case '密码修改':
        return <Lock className="h-4 w-4 text-blue-500" />
      case '登录失败':
        return <AlertTriangle className="h-4 w-4 text-red-500" />
      default:
        return <Check className="h-4 w-4 text-gray-500" />
    }
  }

  return (
    <div className="container mx-auto py-6 space-y-6">
      {/* 页面标题 */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold">账户设置</h1>
          <p className="text-muted-foreground">管理您的账户安全和通知偏好</p>
        </div>
      </div>

      <div className="grid gap-6 lg:grid-cols-2">
        {/* 左侧：安全设置 */}
        <div className="space-y-6">
          {/* 密码设置 */}
          <Card>
            <CardHeader>
              <CardTitle className="text-lg flex items-center">
                <Lock className="mr-2 h-5 w-5" />
                密码设置
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              {!isChangingPassword ? (
                <div className="space-y-3">
                  <p className="text-sm text-muted-foreground">
                    上次修改密码时间：2024-12-14 16:20:15
                  </p>
                  <Button onClick={() => setIsChangingPassword(true)}>
                    修改密码
                  </Button>
                </div>
              ) : (
                <div className="space-y-4">
                  <div>
                    <Label htmlFor="currentPassword">当前密码</Label>
                    <div className="relative mt-1">
                      <Input
                        id="currentPassword"
                        type={showCurrentPassword ? 'text' : 'password'}
                        value={passwordForm.currentPassword}
                        onChange={(e) => setPasswordForm({...passwordForm, currentPassword: e.target.value})}
                        placeholder="输入当前密码"
                      />
                      <Button
                        type="button"
                        variant="ghost"
                        size="sm"
                        className="absolute right-0 top-0 h-full px-3"
                        onClick={() => setShowCurrentPassword(!showCurrentPassword)}
                      >
                        {showCurrentPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                      </Button>
                    </div>
                  </div>
                  <div>
                    <Label htmlFor="newPassword">新密码</Label>
                    <div className="relative mt-1">
                      <Input
                        id="newPassword"
                        type={showNewPassword ? 'text' : 'password'}
                        value={passwordForm.newPassword}
                        onChange={(e) => setPasswordForm({...passwordForm, newPassword: e.target.value})}
                        placeholder="输入新密码（至少8位）"
                      />
                      <Button
                        type="button"
                        variant="ghost"
                        size="sm"
                        className="absolute right-0 top-0 h-full px-3"
                        onClick={() => setShowNewPassword(!showNewPassword)}
                      >
                        {showNewPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                      </Button>
                    </div>
                  </div>
                  <div>
                    <Label htmlFor="confirmPassword">确认新密码</Label>
                    <div className="relative mt-1">
                      <Input
                        id="confirmPassword"
                        type={showConfirmPassword ? 'text' : 'password'}
                        value={passwordForm.confirmPassword}
                        onChange={(e) => setPasswordForm({...passwordForm, confirmPassword: e.target.value})}
                        placeholder="再次输入新密码"
                      />
                      <Button
                        type="button"
                        variant="ghost"
                        size="sm"
                        className="absolute right-0 top-0 h-full px-3"
                        onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                      >
                        {showConfirmPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                      </Button>
                    </div>
                  </div>
                  <div className="flex space-x-2">
                    <Button onClick={handlePasswordChange} disabled={isSaving}>
                      <Save className="mr-2 h-4 w-4" />
                      {isSaving ? '保存中...' : '保存密码'}
                    </Button>
                    <Button variant="outline" onClick={() => setIsChangingPassword(false)}>
                      取消
                    </Button>
                  </div>
                </div>
              )}
            </CardContent>
          </Card>

          {/* 安全设置 */}
          <Card>
            <CardHeader>
              <CardTitle className="text-lg flex items-center">
                <Shield className="mr-2 h-5 w-5" />
                安全设置
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="flex items-center justify-between">
                <div className="space-y-0.5">
                  <Label>两步验证</Label>
                  <p className="text-sm text-muted-foreground">
                    启用两步验证以提高账户安全性
                  </p>
                </div>
                <Switch
                  checked={securitySettings.twoFactorAuth}
                  onCheckedChange={(checked) => handleSecuritySettingChange('twoFactorAuth', checked)}
                />
              </div>
              <Separator />
              <div className="flex items-center justify-between">
                <div className="space-y-0.5">
                  <Label>登录通知</Label>
                  <p className="text-sm text-muted-foreground">
                    在新设备登录时发送邮件通知
                  </p>
                </div>
                <Switch
                  checked={securitySettings.loginNotifications}
                  onCheckedChange={(checked) => handleSecuritySettingChange('loginNotifications', checked)}
                />
              </div>
              <Separator />
              <div className="flex items-center justify-between">
                <div className="space-y-0.5">
                  <Label>可疑活动警报</Label>
                  <p className="text-sm text-muted-foreground">
                    检测到可疑活动时发送警报
                  </p>
                </div>
                <Switch
                  checked={securitySettings.suspiciousActivityAlerts}
                  onCheckedChange={(checked) => handleSecuritySettingChange('suspiciousActivityAlerts', checked)}
                />
              </div>
              <Separator />
              <div className="space-y-2">
                <Label>会话超时时间（分钟）</Label>
                <select
                  value={securitySettings.sessionTimeout}
                  onChange={(e) => handleSecuritySettingChange('sessionTimeout', parseInt(e.target.value))}
                  className="w-full px-3 py-2 border border-input rounded-md bg-background text-sm"
                >
                  <option value={15}>15分钟</option>
                  <option value={30}>30分钟</option>
                  <option value={60}>1小时</option>
                  <option value={120}>2小时</option>
                  <option value={480}>8小时</option>
                </select>
              </div>
            </CardContent>
          </Card>
        </div>

        {/* 右侧：通知设置和账户活动 */}
        <div className="space-y-6">
          {/* 通知设置 */}
          <Card>
            <CardHeader>
              <CardTitle className="text-lg flex items-center">
                <Bell className="mr-2 h-5 w-5" />
                通知设置
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="flex items-center justify-between">
                <div className="space-y-0.5">
                  <Label>邮件通知</Label>
                  <p className="text-sm text-muted-foreground">
                    接收重要通知的邮件
                  </p>
                </div>
                <Switch
                  checked={notificationSettings.emailNotifications}
                  onCheckedChange={(checked) => handleNotificationSettingChange('emailNotifications', checked)}
                />
              </div>
              <Separator />
              <div className="flex items-center justify-between">
                <div className="space-y-0.5">
                  <Label>推送通知</Label>
                  <p className="text-sm text-muted-foreground">
                    在浏览器中显示推送通知
                  </p>
                </div>
                <Switch
                  checked={notificationSettings.pushNotifications}
                  onCheckedChange={(checked) => handleNotificationSettingChange('pushNotifications', checked)}
                />
              </div>
              <Separator />
              <div className="flex items-center justify-between">
                <div className="space-y-0.5">
                  <Label>系统更新</Label>
                  <p className="text-sm text-muted-foreground">
                    接收系统功能更新通知
                  </p>
                </div>
                <Switch
                  checked={notificationSettings.systemUpdates}
                  onCheckedChange={(checked) => handleNotificationSettingChange('systemUpdates', checked)}
                />
              </div>
              <Separator />
              <div className="flex items-center justify-between">
                <div className="space-y-0.5">
                  <Label>安全警报</Label>
                  <p className="text-sm text-muted-foreground">
                    接收安全相关的重要警报
                  </p>
                </div>
                <Switch
                  checked={notificationSettings.securityAlerts}
                  onCheckedChange={(checked) => handleNotificationSettingChange('securityAlerts', checked)}
                />
              </div>
              <Separator />
              <div className="flex items-center justify-between">
                <div className="space-y-0.5">
                  <Label>营销邮件</Label>
                  <p className="text-sm text-muted-foreground">
                    接收产品推广和活动信息
                  </p>
                </div>
                <Switch
                  checked={notificationSettings.marketingEmails}
                  onCheckedChange={(checked) => handleNotificationSettingChange('marketingEmails', checked)}
                />
              </div>
            </CardContent>
          </Card>

          {/* 账户活动 */}
          <Card>
            <CardHeader>
              <CardTitle className="text-lg">最近的账户活动</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-3">
                {accountActivity.map((activity) => (
                  <div key={activity.id} className="flex items-start space-x-3 p-3 rounded-lg border">
                    <div className="mt-1">
                      {getActionIcon(activity.action)}
                    </div>
                    <div className="flex-1 space-y-1">
                      <div className="flex items-center justify-between">
                        <span className="text-sm font-medium">{activity.action}</span>
                        {getStatusBadge(activity.status)}
                      </div>
                      <p className="text-xs text-muted-foreground">
                        {activity.location} • {activity.ip}
                      </p>
                      <p className="text-xs text-muted-foreground">
                        {activity.device}
                      </p>
                      <p className="text-xs text-muted-foreground">
                        {activity.timestamp}
                      </p>
                    </div>
                  </div>
                ))}
              </div>
              <div className="mt-4 text-center">
                <Button variant="outline" size="sm">
                  查看全部活动
                </Button>
              </div>
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  )
}
